<template>
  <div class="user-front">
    <el-menu
        default-active="/shopIndex"
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        router
        :ellipsis="false"
      >
      <p>智慧买药</p>
      <div class="flex-grow"/>
      <el-menu-item index="/shopIndex">首页</el-menu-item>
      <el-menu-item index="/shoppingCart">购物车</el-menu-item>
      <el-menu-item index="/userInfo">个人中心</el-menu-item>
      <el-sub-menu index="3">
        <template>{{ userProfile.userName }}</template>
        <el-menu-item @click="logout">退出登录</el-menu-item>
      </el-sub-menu>
    </el-menu>
    <el-main>
      <router-view/>
    </el-main>
  </div>
</template>
<script setup>
import {onMounted, ref} from 'vue';
import {ElMessage} from 'element-plus';
import {useRouter} from 'vue-router';
import {localGet, localRemove} from "@/utils";
import {doLogout, profile} from "@/api/user"; // 引入 useRouter
const router = useRouter(); // 获取路由实例
// 使用pinia
import { useLoginStore } from '@/store/login.js'

const store = useLoginStore()

// 个人中心数据
const userProfile = ref({});


onMounted(() => {
  // 获取用户信息
  console.log('获取用户信息', localGet('token'));
  getUserInfo()
});

const getUserInfo = async () => {

  await profile({token:localGet('token')}).then((res) => {
    const userInfo = res.data.data
    console.log('userInfo', userInfo);
    // store.profile(userInfo)
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    userProfile.value = userInfo
    // 刷新页面
  }).catch(e => {

  })
}

// 退出登录
const logout = async () => {
  await doLogout({'token':localGet('token')}).then(() => {
    // 退出之后，将本地保存的 token  清理掉
    localRemove('token')
    store.logout()
    // 回到登录页
    router.push({ path: '/login' })
  })
}


const activeIndex = ref('/shopIndex')

</script>

<style scoped>
.flex-grow {
  flex-grow: 1;
}
.user-front {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #545c64;
  padding: 0 20px;
}

.user-info {
  color: #fff;
}

.el-dropdown-link {
  cursor: pointer;
  color: #fff;
}

.el-main {
  margin-top: 20px;
}

.el-card {
  margin-bottom: 20px;
}
</style>